
#include <cstdio>
#include "member_BSharedMemory.h"

using namespace BWE;

member_BSharedMemory::member_BSharedMemory(BSharedMemory* serialPort)
{
	boss = serialPort;
	mode = IO_None;
	error = BSharedMemory::Error_None;
	size = 0;
	buffer = 0;
#ifdef linux
	key = -1;
#endif
#ifdef _WIN32
	shrmem = INVALID_HANDLE_VALUE;
#endif
}
member_BSharedMemory::~member_BSharedMemory()
{

}

void member_BSharedMemory::freshComState()
{
#ifdef linux
	struct termios newtio, oldtio;
	if (tcgetattr(hcom, &oldtio) != 0)
	{
		perror("SetupSerial 1");
		printf("tcgetattr( fd,&oldtio) -> %d\n", tcgetattr(hcom, &oldtio));
		return;
	}
	bzero(&newtio, sizeof(newtio));
	newtio.c_cflag |= CLOCAL | CREAD;
	newtio.c_cflag &= ~CSIZE;
	switch (dataBits)
	{
	case BSharedMemory::Data5:
		newtio.c_cflag |= CS5;
		break;
	case BSharedMemory::Data6:
		newtio.c_cflag |= CS6;
		break;
	case BSharedMemory::Data7:
		newtio.c_cflag |= CS7;
		break;
	case BSharedMemory::Data8:
		newtio.c_cflag |= CS8;
		break;
	}
	switch (parity)
	{
	case BSharedMemory::ParityOdd:
		newtio.c_cflag |= PARENB;
		newtio.c_cflag |= PARODD;
		newtio.c_iflag |= (INPCK | ISTRIP);
		break;
	case BSharedMemory::ParityEven:
		newtio.c_iflag |= (INPCK | ISTRIP);
		newtio.c_cflag |= PARENB;
		newtio.c_cflag &= ~PARODD;
		break;
	case BSharedMemory::ParityMark:
		break;
	case BSharedMemory::ParitySpace:
		break;
	default:
		newtio.c_cflag &= ~PARENB;
		break;
	}
	switch (baudRate)
	{
	case BSharedMemory::Baud1200:
		cfsetispeed(&newtio, B1200);
		cfsetospeed(&newtio, B1200);
		break;
	case BSharedMemory::Baud2400:
		cfsetispeed(&newtio, B2400);
		cfsetospeed(&newtio, B2400);
		break;
	case BSharedMemory::Baud4800:
		cfsetispeed(&newtio, B4800);
		cfsetospeed(&newtio, B4800);
		break;
	case BSharedMemory::Baud9600:
		cfsetispeed(&newtio, B9600);
		cfsetospeed(&newtio, B9600);
		break;
	case BSharedMemory::Baud19200:
		cfsetispeed(&newtio, B19200);
		cfsetospeed(&newtio, B19200);
		break;
	case BSharedMemory::Baud38400:
		cfsetispeed(&newtio, B38400);
		cfsetospeed(&newtio, B38400);
		break;
	default:
		cfsetispeed(&newtio, B9600);
		cfsetospeed(&newtio, B9600);
		break;
	}
	switch (stopBits)
	{
	case BSharedMemory::StopOne:
		newtio.c_cflag &= ~CSTOPB;
		break;
	case BSharedMemory::StopOneAndHalf:
		break;
	case BSharedMemory::StopTwo:
		newtio.c_cflag |= CSTOPB;
		break;
	default:
		newtio.c_cflag = 0;
		break;
	}

	newtio.c_cc[VTIME] = 0;
	newtio.c_cc[VMIN] = 0;
	tcflush(hcom, TCIFLUSH);
	if ((tcsetattr(hcom, TCSANOW, &newtio)) != 0)
	{
		perror("com set error");
	}
#endif

#ifdef _WIN32
	if (shrmem == INVALID_HANDLE_VALUE)
		return;
#endif
}

const char* member_BSharedMemory::checkError()
{
	const char* errorStr = 0;
#ifdef _WIN32
	DWORD error = GetLastError();
	switch (error)
	{
	case ERROR_FILE_NOT_FOUND:
		errorStr = "SerialPort cannot be found.";
		break;

	case ERROR_INVALID_PARAMETER:
		errorStr = "SerialPort parameter is invalid.";
		break;
	}
#endif
	return errorStr;
}